import { getHttp,http } from './http';
import { problem } from './protobuf-loader';
import { getToken } from '../utils/auth';

// 获取proto类型
const ProblemListRequest = problem.ProblemListRequest;
const ProblemListResponse = problem.ProblemListResponse;
const ProblemDetailRequest = problem.ProblemDetailRequest;
const ProblemDetailResponse = problem.ProblemDetailResponse;
const DiscussionListRequest = problem.DiscussionListRequest;
const DiscussionListResponse = problem.DiscussionListResponse;
const SubmitRequest = problem.SubmitRequest;
const SubmitResponse = problem.SubmitResponse;

/**
 * 获取题目列表
 * @param {Object} params 查询参数
 * @returns {Promise<{problems: Array, total: number}>}
 */
export const getProblemList = async (params = {}) => {
  try {
    const token = getToken();
    if (!token) throw new Error('未登录');
    
    const request = new ProblemListRequest();
    request.setToken(token);
    // 确保所有字段都有有效值
    request.setPage(params.page || 1);
    request.setPagesize(params.pageSize || 10);
    request.setDifficulty(params.difficulty || 0);
    request.setSolvedstatus(params.solvedStatus || 0);
    request.setSortby(params.sortBy || 1);
    if (params.searchQuery) {
      request.setSearchquery(params.searchQuery);
    }
    
    const responseData = await getHttp().post('/problem/list', 
      request.serializeBinary());

    const response = ProblemListResponse.deserializeBinary(responseData.data);
    return {
      problems: response.getProblemsList().map(p => {
        const obj = p.toObject();
        return {
          ...obj,
          problemId: obj.id,
          problemTitle: obj.title,
          difficultyLevel: obj.difficulty
        };
      }),
      total: response.getTotal()
    }
  } catch (error) {
    console.error('获取题目列表失败:', error);
    throw error;
  }
};

/**
 * 获取题目详情
 * @param {string} id 题目ID
 * @returns {Promise<Object>}
 */
export const getProblemDetail = async (id) => {
  try {
    const token = getToken();
    if (!token) throw new Error('未登录');
    
    const request = new ProblemDetailRequest();
    request.setToken(token);
    request.setId(id);
    
    const responseData = await getHttp().post('/problem/detail',
      request.serializeBinary());

    const response = ProblemDetailResponse.deserializeBinary(responseData.data);
    const problem = response.getProblem();
    return {
      id: problem.getId(),
      title: problem.getTitle(),
      description: problem.getDescription(),
      difficulty: problem.getDifficulty(),
      tags: problem.getTagsList(),
      testCaseHint: problem.getTestCaseHintList(),
      template: problem.getTemplatesMap()?.toObject() || {},
      testCases: problem.getTestCasesList().map(tc => ({
        input: tc.getInput(),
        output: tc.getOutput(),
        explanation: tc.getExplanation()
      }))
    };
  } catch (error) {
    console.error('获取题目详情失败:', error);
    throw error;
  }
};

/**
 * 提交题目解答
 * @param {string} problemId 题目ID
 * @param {string} code 解答代码
 * @returns {Promise<Object>}
 */
export const submitSolution = async (params) => {
  try {
    const token = getToken();
    if (!token) throw new Error('未登录');
    
    const request = new SubmitRequest();
    request.setToken(token);
    request.setProblemId(params.problemId);
    request.setCode(params.code);
    request.setLanguage(params.language)
    request.setSubmit(params.submit)
    if (params.submit == false) {
      request.setTestData(params.testData)
    }
    
    const responseData = await getHttp().post('/problem/submit', 
      request.serializeBinary());

    const response = SubmitResponse.deserializeBinary(responseData.data);
    return {
      success: responseData.status === 200,
      result: {
        accepted:response.getAccepted(),
        message:response.getMessage(),
        time_cost:response.getTimeCost(),
        memory_cost:response.getMemoryCost(),
        code:response.getCode(),
        language: response.getLanguage()
      }
    };
  } catch (error) {
    console.error('提交解答失败:', error);
    throw error;
  }
};
export const getSubmissions = async (id, page, pagesize) =>{
  // 
  try{
    const request = new problem.SubmissionListRequest();
    request.setToken(getToken());
    request.setProblemId(id);
    request.setPage(page);
    request.setPageSize(pagesize);
    const responseData = await getHttp().post('/problem/submissionlist', 
      request.serializeBinary());
    const response = problem.SubmissionListResponse.deserializeBinary(responseData.data);
    
    return {
      success: responseData.status == 200,
      result: {
        list: response.getResultList().map(re => ({
          id:re.getId(),
          status: re.getAccepted(),
          language: re.getLanguage(),
          time: re.getTime()
        })),
        total: response.getTotal()
      }
    }
  }catch(error) {
    console.log('获取提交记录的信息列表失败',error);
    return {
      list: [],
      total: 0
    }
  }
}
/**
 * 获取提交记录的列表信息
 * @param {string} id 题目的id
 * @returns 提交记录的详细内容
 */
export const getSubmissionDetail = async (id) => {
  // 
  try{
    const request = new problem.SubmissionDetailRequest();
    request.setToken(getToken());
    request.setId(id);
    const responseData = await getHttp().post('/problem/submissiondetail', 
      request.serializeBinary());
    const response = problem.SubmitResponse.deserializeBinary(responseData.data);
    return {
      success: responseData.status === 200,
      result: {
        accepted: response.getAccepted(),
        time_cost: response.getTimeCost(),
        memory_cost: response.getMemoryCost(),
        code: response.getCode(),
        language: response.getCode()
      }
    }
    // return {
    //   status: ,
    //   time: ,
    //   memory: ,
    //   code: ,
    //   language: 
    // }
  }catch(error) {
    console.log('获取提交记录信息失败',error);
    return {}
  }
}
/**
 * 获取用户题目列表(统一处理已通过和尝试中题目)
 * @param {string} userId 用户ID 
 * @param {string} type 题目类型 (solved/attempting)
 * @param {number} page 页码
 * @param {number} pageSize 每页数量
 * @returns {Promise<{problems: Array, total: number, page: number, pageSize: number, totalPages: number}>}
 */
export const getUserProblems = async (email, type = true, page = 1, pageSize = 10) => {
    try {
      const token = getToken();
      if (!token) throw new Error('未登录');
      
      const request = new problem.UserProblemListRequest();
      request.setToken(token);
      request.setEmail(email);
      request.setPage(page);
      request.setPageSize(pageSize);
      request.setSolved(type); // 0: solved, 1: attempting
      
      const responseData = await getHttp().post('/user/problems', 
        request.serializeBinary());
      const response = problem.UserProblemListResponse.deserializeBinary(responseData.data);
      
      return {
        problems: response.getProblemsList().map(p => {
          const obj = p.toObject();
          return {
            ...obj,
            problemId: obj.id,
            problemTitle: obj.title,
            difficultyLevel: obj.difficulty
          };
        }),
        page,
        pageSize
      };
    } catch (error) {
      console.error('获取题目列表失败:', error);
      return {
        problems: [],
        total: 0,
        page,
        pageSize,
        totalPages: 0
      };
    }
  };